<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>4_getSnapshotBeforeUpdate应用场景</title>
    <style>
        .list {
            width: 200px;
            height: 150px;
            background-color: skyblue;
            overflow: auto;
        }

        .news {
            height: 30px;
        }
    </style>
</head>

<body>
<div id="test"></div>
<script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
<script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
<script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

<script type="text/babel">
    /**
     * 1. 初始化阶段: 由ReactDOM.render()触发---初次渲染
         1.constructor()
         2.getDerivedStateFromProps
         3.render()
         4.componentDidMount()
     2. 更新阶段: 由组件内部this.setSate()或父组件重新render触发
         1.getDerivedStateFromProps
         2.shouldComponentUpdate()
         3.render()
         4.getSnapshotBeforeUpdate
         5.componentDidUpdate()
     3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
         1.componentWillUnmount()`
     */
    //创建组件
    class NewList extends React.Component {
        state = {newsArr: []};
        componentDidMount() {
            setInterval(() => {
                //获取原来的状态
                const {newsArr} = this.state
                //模拟一条新闻
                const news = '新闻' + (newsArr.length + 1)
                //更新状态
                this.setState({newsArr: [news, ...newsArr]})
            }, 1000)
        }

        render() {
            return (
                <div className="list" ref="list">
                    {this.state.newsArr.map((n, index) => {
                        return <div key={index} className="news">{n}</div>
                    })}
                </div>
            )
        }

        getSnapshotBeforeUpdate() {
            return this.refs.list.scrollHeight
        }

        componentDidUpdate(preProps, prestate, height) {
            this.refs.list.scrollTop += this.refs.list.scrollHeight - height
        }
    }


    //渲染组件
    ReactDOM.render(<NewList/>, document.getElementById('test'));

</script>
</body>

</html>
